import React, { useState, useCallback, useEffect } from 'react'
import request from '@/utils/request'
import { withUser } from '@/utils/hoc'
import { withRouter } from 'react-router-dom'
import PropTypes from "prop-types";

import {
    message,
    Form,
    Input,
    Button,
    Upload,
    Radio,
    Select,
    Cascader,
    DatePicker,
    InputNumber,
    TreeSelect,
    Switch,
    Rate,
    Modal,
    Image
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
// import { use } from '../../../../../manageApi/routes/hotTV';

// "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2709863550.jpg"
function InterviewForm(props) {
    var data={
        "American":"美剧",
        "Britain":"英剧",
        "China":"国产剧",
        "HongKong":"港剧",
        "Japan":"日剧",
        "JapaneseAnimation":"日本动画",
        "SouthKorea":"韩剧",
        "documentary":"纪录片",
        "variety":"综艺"
    }
    const dataKeys=Object.keys(data)
    // console.log(Object.keys(data));
    // var state
    // const { data: { data: state } } = props
    // const [state,setState]=useState({})
    // const reg = /\/edit/
    // if (reg.test(props.props.match.url)) {
    //     const { data: { data } } = props
    //     setState(data)
    //     // state = data
    // }

    console.log("props", props);
    const [form] = Form.useForm()
    const isEdit = !!props.data.data;
    if (!props.data.data && isEdit) {
        return (
            <></>
        )
    }
    // const {poster}=state
    const [previewVisible, setPreviewVisible] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [previewTitle, setPreviewTitle] = useState('')

    const [fileList, setFileList] = useState([])
    const [select, setSelect] = useState('')

    const getBase64 = function (file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }


    const handleCancel = () => setPreviewVisible(false);
    const handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);

        }
        setPreviewImage(file.url || file.preview)

        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
        setPreviewVisible(true)
        // this.setState({
        //     previewImage: file.url || file.preview,
        //     previewVisible: true,
        //     previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        //   });
    }
    const handleChange = useCallback(({ fileList }) => {
        console.log("fileList", fileList[0]);
        console.log("fileList[0].thumbUrl", fileList[0].thumbUrl);
        console.log("fileList[0].uid", fileList[0].uid);
        setFileList(fileList);
    }, [])
    const beforeUpload = function (file, fileList) {
        // console.log("file", file.thumbUrl);
    }
    const selectChange=useCallback((value)=>{
        // console.log('select',value);
        setSelect(value)
    },[])
    const onFinish = useCallback(async function (TvObj) {

        // beforeUpload()
        // console.log(TvObj);
        const url = props.props.match.url.split('/')[3]
        // console.log("values====", url);
        if (isEdit) {
            const { data } = await request.patch(`/patchTVlist/patch`, {
                TvObj,
                collectionName: url
            })

            if (data.code === 200) {
                message.success('修改成功')
                console.log(props.props);
                console.log(props.props.match.path.replace('/' + url, '') + `/${url}`);
                props.props.history.push(props.props.match.path.replace(props.props.match.path, '') + `/manage/interview/${url}`);
            }
        } else {

            // const date=new Date()
            var timestamp = new Date().getTime()
            // console.log("addTvObj",TvObj,timestamp);
            TvObj.doubanId = timestamp
            // if(!select){
                
            // }
            console.log('TvObj========',select);
            const { data } = await request.post(`/addTVlist/add`,
                { TvObj, collectionName:select  }
            )
           
            if (data.code === 200) {
                message.success('添加成功');
                props.props.history.push(props.props.match.path.replace(props.props.match.path, '') + `/manage/interview/${url}`);
                // history.push('/manage/interview/list')
            }

        }
    }, [select])
   
    // 编辑状态
    if (isEdit) {
        form.setFieldsValue(props.data.data)
        // console.log("state",state);
    }
    // const { loading, imageUrl } = this.state;
    // const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const selectAfter = (
        <Select defaultValue="请选择" onChange={selectChange}>
            {dataKeys.map((item)=>{
                return <Option key={item} value={item}>{data[item]}</Option>
            })}
            {/* <Option value=".com">{Object.keys(data)}</Option>
            <Option value=".jp">.jp</Option>
            <Option value=".cn">.cn</Option>
            <Option value=".org">.org</Option> */}
        </Select>
    );
    // if(fileList){
    //     return(
    //         <></>
    //     )
    // }
    // var url = `http://localhost:3000/hotTV/patchhotTv`
    return (
        <Form
            labelCol={{
                span: 4,
            }}
            wrapperCol={{
                span: 18,
            }}
            layout="horizontal"
            form={form}
            onFinish={onFinish}
        >
            <Form.Item
                label="doubanId"
                name="doubanId"
                hidden
            >
                <Input />
            </Form.Item>
            <Form.Item label="剧名" name="title">
                <Input />
            </Form.Item>
            {isEdit?<></>:<Form.Item label="类型" >
                
                {/* <Select size={size} defaultValue="a1" onChange={handleChange} style={{ width: 200 }}>
                    {children}
                </Select> */}
                {/* <Input.Group compact > */}
                    
                        {selectAfter}
                    
                {/* </Input.Group> */}
            </Form.Item>}

            {/* <Form.Item label="分类" name="category">
                        <Select>
                            <Select.Option value="demo">Demo</Select.Option>
                        </Select>
                    </Form.Item> */}

            {/* <Form.Item label="DatePicker">
                        <DatePicker />
                    </Form.Item> */}
            <Form.Item label="评分" name="rate">
                <InputNumber />
                {/* <Rate value="3" /> */}
            </Form.Item>
            {isEdit ? (<Form.Item label="封面" name="poster">
                <Image
                    width={80}
                    src={props.data.data.poster}
                />
            </Form.Item>) : <></>

            }


            <Form.Item label={isEdit ? "修改封面" : '添加封面'} name="poster">

                <Upload
                    method='PATCH'
                    action={`http://10.3.144.22:3001/hotTV/patchhotTv`}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={handlePreview}
                    onChange={handleChange}
                    beforeUpload={beforeUpload}
                // data={{ doubanId: props.data.data.doubanId }}
                >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={handleCancel}
                >
                    <img alt="example" style={{ width: '100%' }} src={(previewImage)} />
                </Modal>
            </Form.Item>
            {/* <Form.Item label="审核" name="checked" valuePropName="checked">
                <Switch />
            </Form.Item> */}
            <Form.Item wrapperCol={{
                offset: 4,
            }}>
                <Button type="primary" htmlType="submit">提交</Button>
            </Form.Item>
        </Form>
    )
}

// props数据类型校验
// InterviewForm.propTypes = {
//     data: PropTypes.object,

//     // 定义data对象的属性类型
//     // data:PropTypes.shape({
//     //     doubanId: PropTypes.string,
//     //     question: PropTypes.string.isRequired
//     // })
// };

// // props默认值
// // InterviewForm.defaultProps = {
// //     data:{}
// // }

// InterviewForm = withUser(InterviewForm)
// InterviewForm = withRouter(InterviewForm)

export default InterviewForm